package com.unionftech.common.webview.view

import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.net.http.SslError
import android.webkit.SslErrorHandler
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.webview.callback.WebViewCallBack

class BaseWebViewClient(
    private val webView: WebView,
    private var webViewCallBack: WebViewCallBack? = null,
    private val mHeaders: HashMap<String, String>?,
    private val mWebViewTouch: WebViewTouch,
    private val redirectIntercept: Boolean
) : WebViewClient() {

    /**
     * 是否加载完成
     */
    var isReady = false

    interface WebViewTouch {
        fun isTouchByUser(): Boolean
    }

    /**
     * url重定向会执行此方法以及页面某些链接也会执行此方法
     * @return true:表示当前url已经加载完成，即使url还会重定向都不会再进行加载;
     *         false:表示此url默认由系统处理，该重定向还是会重定向，直到加载完成
     */
    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
        LogUtils.d("shouldOverrideUrlLoading url: ${request.url}")
        //当前链接的重定向
        if (!mWebViewTouch.isTouchByUser() && !redirectIntercept) {
            return super.shouldOverrideUrlLoading(view, request)
        }
        //如果链接跟当前链接一样，表示刷新
        if (webView.url == request.url.toString()) {
            return super.shouldOverrideUrlLoading(view, request)
        }
        //需要跳转应用的特殊链接
        if (handleLinked(request.url.toString())) {
            return true
        }
        //拦截指定的url
        if (webViewCallBack?.overrideUrlLoading(request.url.toString()) == true) {
            return true
        }
        //控制页面中点开新的连接在当前webView中打开
        view.loadUrl(request.url.toString(), mHeaders ?: HashMap())
        return true

    }

    private fun handleLinked(url: String): Boolean {
        if (url.startsWith(WebView.SCHEME_TEL)
            || url.startsWith(WebView.SCHEME_MAILTO)
            || url.startsWith(WebView.SCHEME_GEO)
            || url.startsWith("sms:")
        ) {
            try {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = Uri.parse(url)
                webView.context.startActivity(intent)
            } catch (ignored: ActivityNotFoundException) {
                ignored.printStackTrace()
            }
            return true
        }
        return false
    }

    override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
        LogUtils.d("onPageStartedV url: $url")
        if (url == null) {
            return
        }
        webViewCallBack?.pageStarted(url)
    }

    override fun onPageFinished(view: WebView?, url: String?) {
        LogUtils.d("onPageFinished url: $url")
        if (url == null) {
            return
        }
        webViewCallBack?.pageFinished(url)
    }

    override fun onScaleChanged(view: WebView?, oldScale: Float, newScale: Float) {
        super.onScaleChanged(view, oldScale, newScale)
    }

    /**
     * 继续加载
     */
    override fun shouldInterceptRequest(
        view: WebView,
        request: WebResourceRequest
    ): WebResourceResponse? {
        return super.shouldInterceptRequest(view, request)
    }


    override fun onReceivedError(
        view: WebView,
        request: WebResourceRequest,
        error: WebResourceError
    ) {

        LogUtils.e(
            "onReceivedError errorCode: ${error.errorCode} " +
                    " description: ${error.description}"
        )
        webViewCallBack?.onError(
            error.errorCode,
            error.description.toString(),
            request.url.toString()
        )
    }

    /**
     * SSL 错误处理
     */
    override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
        LogUtils.d("onReceivedSslError error: ${error.primaryError}")
    }

}
